import db from '../../db.js';
import response from '../../response.js';
import Router from 'koa-router';
const router = new Router();

router.post('/role/menu', async (ctx) => {
  const { roleId, menuIds } = ctx.data || {};
  if (!roleId && roleId !== 0) {
    ctx.body = response.fail({ msg: '角色不能为空' });
    return;
  }
  const [hasRoleRows] = await db.execute('select id from role where id=? limit 1', [roleId]);
  if (!hasRoleRows?.length) {
    ctx.body = response.fail({ msg: '角色不存在' });
    return;
  }
  if (!menuIds?.length) {
    ctx.body = response.fail({ msg: '权限不能为空' });
    return;
  }
  const set = new Set(menuIds);
  const uniqueList = Array.from(set);
  const [hasMenuRows] = await db.execute('select id from menu where id=? limit ?', [
    uniqueList.join(','),
    uniqueList?.length,
  ]);
  if (!hasMenuRows?.length) {
    ctx.body = response.fail({ msg: '权限不存在' });
    return;
  }
  const createTime = new Date().getTime();

  const saveData = hasMenuRows?.map((item) => {
    return [roleId, item?.id, createTime, createTime];
  });
  try {
    const [result] = await db.query(
      'insert into role_menu(roleId,menuId,create_time,hide,update_time) values ?',
      [saveData],
    );
    if (result?.affectedRows > 0) {
      ctx.body = response.success({
        msg: '新增成功',
      });
    } else {
      ctx.body = response.fail({
        msg: '新增失败',
      });
    }
  } catch (e) {
    ctx.body = response.fail({
      msg: '新增失败',
    });
  }
});

router.get('/role/menu/:roleId', async (ctx) => {
  const { roleId } = ctx.params || {};
  if (!roleId && roleId !== 0) {
    ctx.body = response.fail({ msg: '角色不能为空' });
    return;
  }
  try {
    const [rows] = await db.query('select roleId,menuId from role_menu where roleId=?', [roleId]);
    ctx.body = response.success({ data: rows });
  } catch (e) {
    ctx.body = response.error({ msg: e });
  }
});
router.get('/role/menuList/:roleId', async (ctx) => {
  const { roleId } = ctx.params || {};
  if (!roleId && roleId !== 0) {
    ctx.body = response.fail({ msg: '角色不能为空' });
    return;
  }
  try {
    const [rows] = await db.query(
      'select role_menu.roleId,role_menu.menuId,menu.name,menu.type,menu.code,menu.permission from role_menu left join menu on  role_menu.menuId=menu.id where roleId=?',
      [roleId],
    );
    ctx.body = response.success({ data: rows });
  } catch (e) {
    ctx.body = response.error({ msg: e });
  }
});

router.post('/role/user', async (ctx) => {
  const { roleId, userIds } = ctx.data || {};
  if (!roleId && roleId !== 0) {
    ctx.body = response.fail({ msg: '角色不能为空' });
    return;
  }
  const [hasRoleRows] = await db.execute('select id from role where id=? limit 1', [roleId]);

  if (!hasRoleRows?.length) {
    ctx.body = response.fail({ msg: '角色不存在' });
    return;
  }

  if (!userIds?.length) {
    ctx.body = response.fail({ msg: '用户不能为空' });
    return;
  }
  const set = new Set(userIds);
  const uniqueList = Array.from(set);
  const [hasUserRows] = await db.execute('select id from user where id=? limit ?', [
    uniqueList.join(','),
    uniqueList?.length,
  ]);
  if (!hasUserRows?.length) {
    ctx.body = response.fail({ msg: '用户不存在' });
    return;
  }
  const createTime = new Date().getTime();

  const saveData = hasUserRows?.map((item) => {
    return [roleId, item?.id, createTime, createTime];
  });
  try {
    const [result] = await db.query(
      'insert into role_user(roleId,userId,create_time,update_time) values ?',
      [saveData],
    );
    if (result?.affectedRows > 0) {
      ctx.body = response.success({
        msg: '新增成功',
      });
    } else {
      ctx.body = response.fail({
        msg: '新增失败',
      });
    }
  } catch (e) {
    ctx.body = response.fail({
      msg: '新增失败',
    });
  }
});

router.get('/role/user/:roleId', async (ctx) => {
  const { roleId } = ctx.params || {};
  if (!roleId && roleId !== 0) {
    ctx.body = response.fail({ msg: '角色不能为空' });
    return;
  }
  try {
    const [rows] = await db.query('select roleId,userId from role_user where roleId=?', [roleId]);
    ctx.body = response.success({ data: rows });
  } catch (e) {
    ctx.body = response.error({ msg: e });
  }
});

router.get('/role/userList/:roleId', async (ctx) => {
  const { roleId } = ctx.params || {};
  if (!roleId && roleId !== 0) {
    ctx.body = response.fail({ msg: '角色不能为空' });
    return;
  }
  try {
    const [rows] = await db.query(
      'select role_user.roleId,role_user.userId,user.userName,user.email from role_user left join user on  role_user.userId=user.id where roleId=?',
      [roleId],
    );
    ctx.body = response.success({ data: rows });
  } catch (e) {
    ctx.body = response.error({ msg: e });
  }
});
export default router;
